/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hk.ces.oxfam.patch.patchs;

import hk.ces.oxfam.patch.DBPatch;
import hk.ces.oxfam.patch.config.Config;
import hk.ces.oxfam.patch.connection.ConnectionUtil;
import hk.ces.oxfam.patch.obj.FieldInfo;
import hk.ces.oxfam.patch.obj.TableInfo;
import hk.ces.oxfam.patch.util.StringUtil;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 *
 * @author dev
 */
public class DataDictPatch2 implements DBPatch
{

  private void createTableXml(List<TableInfo> tables)
  {
    Document document = DocumentHelper.createDocument();
    Element tablesElement = document.addElement("Tables");

    Iterator<TableInfo> iterator = tables.iterator();
    while (iterator.hasNext())
    {
      TableInfo info = iterator.next();
      Element tableElement = tablesElement.addElement("table");
      tableElement.addAttribute("name", info.getTableName());

      List<FieldInfo> fields = info.getInfoses();
      Iterator<FieldInfo> it = fields.iterator();
      while (it.hasNext())
      {
        FieldInfo fieldInfo = it.next();
        Element filedElement = tableElement.addElement("filed");
        filedElement.addAttribute("name", fieldInfo.getColumnName());
        filedElement.addAttribute("size", fieldInfo.getSize());
        filedElement.addAttribute("type", fieldInfo.getTypeName());
      }
    }
    try
    {
      OutputFormat format = OutputFormat.createPrettyPrint();
      XMLWriter output = new XMLWriter(new FileWriter(new File("c:/lib/tables.xml")), format);
      output.write(document);
      output.close();
    }
    catch (IOException ex)
    {
      ex.printStackTrace();
    }
  }

  private List<TableInfo> getAllTables(Connection conn)
  {
    List tables = new ArrayList();
    try
    {
      DatabaseMetaData databaseMetaData = conn.getMetaData();

      ResultSet tableSet = databaseMetaData.getCatalogs();

      tableSet = databaseMetaData.getTables(null, "DB2INST1", null, new String[]
      {
        "TABLE"
      });

      while (tableSet.next())
      {
        TableInfo info = new TableInfo();
        String tableName = tableSet.getString("TABLE_NAME");
        info.setTableName(tableName);

        ResultSet columnSet = databaseMetaData.getColumns(null, "DB2INST1", tableName, "%");
        while (columnSet.next())
        {
          FieldInfo fieldinfo = new FieldInfo();
          String columnName = columnSet.getString("COLUMN_NAME");
          String size = columnSet.getString("COLUMN_SIZE");
          String typeName = columnSet.getString("TYPE_NAME");
          String disc = columnSet.getString("REMARKS");
          fieldinfo.setColumnName(StringUtil.ridNullValue(columnName));
          fieldinfo.setSize(StringUtil.ridNullValue(size));
          fieldinfo.setTypeName(StringUtil.ridNullValue(typeName));
          info.getInfoses().add(fieldinfo);
        }
        tables.add(info);
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }

    return tables;
  }

  public static void main(String[] args)
  {
    Config.setCurrentConfigServer(Config.ConfigServer.PRODUCTION);
    Connection connection = ConnectionUtil.openConnection();
    DataDictPatch2 patch = new DataDictPatch2();
    patch.createTableXml(patch.getAllTables(connection));
  }

  public String getName()
  {
    return DataDictPatch2.class.getName();
  }

  public void patch(Connection connection) throws SQLException
  {
    this.createTableXml(this.getAllTables(connection));
  }

  private void modifiedXml(File inputXml)
  {
    SAXReader saxReader = new SAXReader();
    try
    {
      Document document = saxReader.read(inputXml);
      Element tablesElement = document.getRootElement();
      List<Element> elements = tablesElement.selectNodes("table");
      Iterator<Element> iterator = elements.iterator();
      while (iterator.hasNext())
      {
        Element element = iterator.next();
        Attribute attribute = element.attribute("name");
        if (attribute.getValue().equals("BLACKLIST"))
        {
          element.addAttribute("disc", "this's a table about person in blacklist");
        }
      }
      try
      {
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter output = new XMLWriter(new FileWriter(inputXml), format);
        output.write(document);
        output.close();
      }
      catch (IOException ex)
      {
        Logger.getLogger(DataDictPatch2.class).debug(ex.getMessage());
      }
    }
    catch (DocumentException ex)
    {
      Logger.getLogger(DataDictPatch2.class).debug(ex.getMessage());
    }
  }
}
